﻿using System.Collections.ObjectModel;
using MyToDo.Common;
using MyToDo.Extensions;
using MyToDo.Service;
using MyToDo.Shared.Dtos;
using Prism.Commands;
using Prism.Ioc;
using Prism.Regions;
using Prism.Services.Dialogs;

namespace MyToDo.ViewModels
{
    public class ToDoViewModel : NavigationViewModel
    {
        private readonly IDialogHostService dialogHost;

        public ToDoViewModel(IToDoService service, IContainerProvider provider)
            : base(provider)
        {
            ToDoDtos = new ObservableCollection<ToDoDto>();
            ExcuteCommand = new DelegateCommand<string>(Excute);
            SelectedCommand = new DelegateCommand<ToDoDto>(Selected);
            DeleteCommand = new DelegateCommand<ToDoDto>(DeleteAction);
            this.service = service;
            dialogHost = provider.Resolve<IDialogHostService>();
        }

        private async void DeleteAction(ToDoDto toDo)
        {
            var dialogResult = await dialogHost.Question(
                "温馨提示",
                $"确认删除待办事项{toDo.Title}?"
            );
            if (dialogResult.Result != ButtonResult.OK)
            {
                return;
            }
            var result = await service.DeleteAsync(toDo.Id);
            if (result.Status)
            {
                var model = ToDoDtos.FirstOrDefault(t => t.Id.Equals(toDo.Id));
                if (model != null)
                {
                    ToDoDtos.Remove(model);
                }
            }
        }

        private void Excute(string obj)
        {
            switch (obj)
            {
                case "新增":
                    Add();
                    break;

                case "查询":
                    GetDataAsync();
                    break;

                case "保存":
                    Save();
                    break;

                default:
                    break;
            }
        }

        private async void Save()
        {
            if (
                string.IsNullOrWhiteSpace(CurrentDto.Title)
                || string.IsNullOrWhiteSpace(CurrentDto.Content)
            )
            {
                return;
            }
            try
            {
                UpdateLoading(true);
                if (CurrentDto.Id > 0)
                {
                    var updateResult = await service.UpdateAsync(CurrentDto);
                    if (updateResult.Status)
                    {
                        var todo = ToDoDtos.FirstOrDefault(t => t.Id == CurrentDto.Id);
                        if (todo != null)
                        {
                            todo.Title = CurrentDto.Title;
                            todo.Content = CurrentDto.Content;
                            todo.Status = CurrentDto.Status;
                        }
                    }
                    IsRightDrawerOpen = false;
                }
                else
                {
                    var addResult = await service.AddAsync(CurrentDto);
                    if (addResult.Status)
                    {
                        ToDoDtos.Add(addResult.Result);
                        IsRightDrawerOpen = false;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"error is {ex.Message}");
                throw;
            }
            finally
            {
                UpdateLoading(false);
            }
        }

        private int selectedIndex;

        public int SelectedIndex
        {
            get { return selectedIndex; }
            set
            {
                selectedIndex = value;
                RaisePropertyChanged();
            }
        }

        private string search;

        public string Search
        {
            get { return search; }
            set
            {
                search = value;
                RaisePropertyChanged();
            }
        }

        private bool isRightDrawerOpen;

        public bool IsRightDrawerOpen
        {
            get { return isRightDrawerOpen; }
            set
            {
                isRightDrawerOpen = value;
                RaisePropertyChanged();
            }
        }

        public DelegateCommand<string> ExcuteCommand { get; private set; }
        public DelegateCommand<ToDoDto> SelectedCommand { get; private set; }
        public DelegateCommand<ToDoDto> DeleteCommand { get; private set; }

        /// <summary>
        /// 添加待办
        /// </summary>
        private void Add()
        {
            CurrentDto = new ToDoDto();
            IsRightDrawerOpen = true;
        }

        private async void Selected(ToDoDto dto)
        {
            try
            {
                UpdateLoading(true);
                var selectedResult = await service.GetByIdAsync(dto.Id);
                if (selectedResult.Status)
                {
                    CurrentDto = selectedResult.Result;
                    IsRightDrawerOpen = true;
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                UpdateLoading(false);
            }
        }

        private ObservableCollection<ToDoDto> toDoDtos;
        private readonly IToDoService service;
        private ToDoDto currentDto;

        public ToDoDto CurrentDto
        {
            get { return currentDto; }
            set
            {
                currentDto = value;
                RaisePropertyChanged();
            }
        }

        public ObservableCollection<ToDoDto> ToDoDtos
        {
            get { return toDoDtos; }
            set
            {
                toDoDtos = value;
                RaisePropertyChanged();
            }
        }

        private async void GetDataAsync()
        {
            UpdateLoading(true);
            int? Status =
                SelectedIndex == 0 ? null
                : SelectedIndex == 2 ? 1
                : 0;
            var todoResult = await service.GetAllFilterAsync(
                new Shared.Parameters.ToDoParameter()
                {
                    Status = Status,
                    Search = Search,
                    PageIndex = 0,
                    PageSize = 100,
                }
            );
            if (todoResult.Status)
            {
                ToDoDtos.Clear();
                foreach (var item in todoResult.Result.Items)
                {
                    ToDoDtos.Add(item);
                }
            }
            UpdateLoading(false);
        }

        public override void OnNavigatedTo(NavigationContext navigationContext)
        {
            base.OnNavigatedTo(navigationContext);
            if (navigationContext.Parameters.ContainsKey("Value"))
            {
                SelectedIndex = navigationContext.Parameters.GetValue<int>("Value");
            }
            else
            {
                SelectedIndex = 0;
            }
            GetDataAsync();
        }
    }
}